package com.chu.cloud.advice;

import com.chu.cloud.response.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/6/29 17:10
 * @Description:
 */
@RestControllerAdvice("com.chu.cloud.controller")
@Slf4j
public class ResponseMessageAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 不处理全局异常
     *
     * @param methodParameter
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        Class<?> clazz = methodParameter.getContainingClass();
        log.info("Class:{}", methodParameter.getContainingClass());
        return clazz != GlobalExceptionHandler.class;
    }

    /**
     * 这里可以做新老版本接口兼容,新版本接口加密,同时不影响老版本接口,做下版本判断逻辑即可
     *
     * @param body
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        ResponseMessage<Object> response = new ResponseMessage<Object>(HttpStatus.OK.value());
        response.setData(body);
        if (body == null) {
            // when return type of controller method is void
        }
//        else if (body instanceof List) {
//            response.setData((List) body);
//        }
//        else if (body instanceof PageResult) {
//            responseBody.setPageResult((PageResult) body);
//        } else {

//        }

        return response;
    }
}
